const express = require('express')
const router = express.Router()
const models = require('../models')
const { success, error } = require('../utils/message')

// 查询地址列表
router.get('/', async function (req, res, next) {
  const addresses = await models.Address.findAll({
    where: { userId: req.decoded.user.id },
  })

  success(res, '查询成功', { addresses })
})

// 新增
router.post('/', async function (req, res, next) {
  const pca = req.body.pca
  const detail = req.body.detail
  const tel = req.body.tel
  const name = req.body.name

  if (!pca) {
    return error(res, '请选择省市区')
  }

  if (!detail) {
    return error(res, '请填写详细地址')
  }

  if (!tel) {
    return error(res, '请填写联系电话')
  }

  if (!name) {
    return error(res, '请填写姓名')
  }

  const pcaInfo = pca.split(' ')
  const data = {
    ...req.body,
    userId: req.decoded.user.id,
    province: pcaInfo[0],
    city: pcaInfo[1],
    area: pcaInfo[2],
  }

  const address = await models.Address.create(data)
  success(res, '新增成功', { address })
})

// 查询当前记录
router.get('/:id', async function (req, res, next) {
  const id = req.params.id

  const address = await models.Address.findByPk(id)
  if (!address) {
    return error(res, '当前地址不存在')
  }

  success(res, '查询成功', { address })
})

// 修改
router.put('/:id', async function (req, res, next) {
  const id = req.params.id
  const pca = req.body.pca
  const detail = req.body.detail
  const tel = req.body.tel
  const name = req.body.name

  if (!pca) {
    return error(res, '请选择省市区')
  }

  if (!detail) {
    return error(res, '请填写详细地址')
  }

  if (!tel) {
    return error(res, '请填写联系电话')
  }

  if (!name) {
    return error(res, '请填写姓名')
  }

  const address = await models.Address.findByPk(id)
  if (!address) {
    return error(res, '当前地址不存在，无法修改')
  }

  const pcaInfo = pca.split(' ')
  const data = {
    ...req.body,
    userId: req.decoded.user.id,
    province: pcaInfo[0],
    city: pcaInfo[1],
    area: pcaInfo[2],
  }

  address.update(data)
  success(res, '修改成功', { address })
})

// 删除
router.delete('/:id', async function (req, res, next) {
  const id = req.params.id

  const address = await models.Address.findByPk(id)
  if (!address) {
    return error(res, '当前地址不存在，无法删除')
  }

  address.destroy()
  success(res, '删除成功')
})


// 设置用户默认地址
router.patch('/:id/set_default', async function (req, res, next) {
  const id = req.params.id

  const address = await models.Address.findByPk(id)
  if (!address) {
    return error(res, '当前地址不存在，无法设置为默认地址')
  }

  const user = await models.User.findByPk(req.decoded.user.id)
  user.update({ addressId: id })

  success(res, '修改成功', { user })
})

module.exports = router
